const bcrypt = require('bcryptjs')

const { userVerifyError, userAlreadyExists, wrongPassword } = require('../error/errorType')
const { getUserInfo } = require('../service/user_service')

// 验证注册信息是否完整
const userVerify = async (ctx, next) => {
    const { password, username } = ctx.request.body
    if (password && username) {
        await next()
    } else {
        ctx.app.emit('error', userVerifyError, ctx)
    }
}
// 验证用户是否存在
const userIsExist_reg = async (ctx, next) => {
    try {
        const { username } = ctx.request.body
        const res = await getUserInfo({ username })
        // 注册时验证用户是否存在
        if (res?.user_id) {
            ctx.app.emit('error', userAlreadyExists, ctx)
        } else {
            await next()
        }
    } catch (e) {
        console.error('注册验证用户是否存在失败', new Date(), e)
    }
}
const userIsExist_login = async (ctx, next) => {
    try {
        const { username } = ctx.request.body
        const res = await getUserInfo({ username })
        // 登录时验证用户是否存在
        if (!res?.user_id) {
            ctx.app.emit('error', userNotExists, ctx)
        } else {
            await next()
        }

    } catch (e) {
        console.error('登录验证用户是否存在失败', new Date(), e)
    }
}

// 用户密码加盐加密
const crpytPassword = async (ctx, next) => {
    const { password } = ctx.request.body

    const salt = bcrypt.genSaltSync(10)
    // hash保存的是 密文
    const hash = bcrypt.hashSync(password, salt)

    ctx.request.body.password = hash

    await next()
}

// 用户登录验证
const loginVerify = async (ctx, next) => {
    try {
        const { username, password } = ctx.request.body
        const { password: hashpassword } = await getUserInfo({ username })
        let res = bcrypt.compareSync(password, hashpassword)
        if (res) {
            await next()
        } else {
            ctx.app.emit('error', wrongPassword, ctx)
        }
    } catch (e) {
        console.error('用户登录验证失败', new Date(), e)
    }
}

module.exports = {
    userVerify,
    userIsExist_reg,
    userIsExist_login,
    crpytPassword,
    loginVerify
}